<?php
Class C_index extends Cemvc_Control_Base
{
  private $db;
  public function __construct()
  {
    parent::__construct();
    $this->db = new M_qin_users();
    /* $this->db->SetDbCodeNames("utf8"); */
    /* print_r($_SESSION); */

    $this->view->assign("default_user", DEFAULT_USER_IN_HOME);
  }

  public function index()
  {
	  M_Tools::check_photo_wall();
	  M_Tools::check_surnames();
	  M_Tools::check_hot_people();
	  M_Tools::check_latest_people();
    /* redirect old link from other sites to /tree/index */
    $userid = null;
    if (isset($_REQUEST["userid"]) && $_REQUEST["userid"])
      $userid = $_REQUEST["userid"];
    if (isset($_REQUEST["id"]) && $_REQUEST["id"])
      $userid = $_REQUEST["id"];
    if($userid)
      {
	header('HTTP/1.1 404 Not Found'); 
	$this->redirect("tree/index?userid=".$_REQUEST["userid"]);
	return;
      }

    if ($this->Role == ROLE_GUEST)
      {
	/* get user information from users table */
	if (!isset($_SESSION["id"]) || empty($_SESSION["id"]))
	  {
	    if (isset($_REQUEST['openid']) && $_REQUEST['openid'] &&
		isset($_REQUEST["openkey"]) && $_REQUEST["openkey"] &&
		isset($_REQUEST["pf"]) && $_REQUEST["pf"])
	      {
		// FIXME: debug for css, you should remove it after change server in qq open app
		$_SESSION["openid"] = $_REQUEST["openid"];
		// FIXME: END 
		$res = M_QQ::is_login($_REQUEST["openid"], $_REQUEST["openkey"], $_REQUEST["pf"]);
		if ($res["ret"] === 0)
		  {
		    $_SESSION["openid"] = $_REQUEST["openid"];
		    $_SESSION["openkey"] = isset($_REQUEST['openkey']) ? $_REQUEST['openkey'] : '';
		    $_SESSION["pf"] = isset($_REQUEST["pf"]) ? $_REQUEST["pf"] : DEFAULT_QQ_PF;
		    $_SESSION["pfkey"] = isset($_REQUEST["pfkey"]) ? $_REQUEST["pfkey"] : '';

		    $user = $this->db->get_user_with_openid('pengyou', $_SESSION["openid"]);
		    if ($user && isset($user['id']))
		      {
			/* found this user */
			$_SESSION = array_merge($_SESSION, $user);
		      }
		    else
		      {
			/* not found in user table */
			/* get user info through QQ API */
			$info = M_QQ::get_user_info($_REQUEST["openid"], $_REQUEST["openkey"], $_REQUEST["pf"]);
			
			/* register */
			$para = array("realname"=>$info["nickname"],
				      "gender"  =>$info["gender"]=='男' ? MALE : FEMALE,
				      "qq_open_id" => $_REQUEST["openid"]);
			$user = $this->db->add($para);
			$_SESSION = array_merge($_SESSION, $user);
		      }
		    $this->setRole(ROLE_MEMBER);
		  }
	      }

	    else if (isset($_REQUEST["code"]) && $_REQUEST["code"])
	    {
		    M_Tools::print_r($_SESSION,1);
		    // oauth return from qq.com
		    if ($_SESSION['oauth'] == OAUTH_TYPE_QQ)
		    {
			$res = M_Oauth::auth_qq($_REQUEST['code']);
		    }
		    // oauth return from kaixin001
		    else if ($_SESSION['oauth'] == OAUTH_TYPE_KAIXIN)
		    {
			$res = M_Oauth::auth_kaixin($_REQUEST['code']);
			if (!$res)
			{
				header("Location: /users/login");
				die();
			}
		    }
		    // oauth return from renren
		    else if ($_SESSION['oauth'] == OAUTH_TYPE_RENREN)
		    {
			$res = M_Oauth::auth_renren($_REQUEST['code']);
		    }
		    // oauth return from sina weibo
		    else if ($_SESSION['oauth'] == OAUTH_TYPE_WEIBO)
		    {	
				
			    M_Tools::log('error'.$res['message'], 1);
			$res = M_Oauth::auth_weibo($_REQUEST['code']);
		    }
		    M_Tools::print_r($res, 1);
		    if (isset($res['error']) && $res['error'])
		    {
			    M_Tools::log('error'.$res['message'], 1);
			    $this->redirect("users/login?msg=".urlencode($res['message']));
			    return;
		    }	
		    $_SESSION = array_merge($_SESSION, $res);
		    $this->setRole(ROLE_MEMBER);
		    header("Location: /");
		    return;
	    }
	  }
	else
		$this->setRole(ROLE_MEMBER);
	//$this->redirect("tree/index?userid=".DEFAULT_USER_IN_HOME);
      }

    $this->display();
  }
  public function get_access_token_from_sina_weibo()
  {
	  $url = "https://api.weibo.com/oauth2/access_token";
	  $data = "client_id=".OAUTH_SINA_APP_KEY."&client_secret=".OAUTH_SINA_SECRET_KEY."&grant_type=authorization_code&redirect_uri=".OAUTH_SINA_REDIRECT_URI."&code=".$_REQUEST["code"];
	  $ch = curl_init();
	  curl_setopt($ch, CURLOPT_POST, 1);
	  curl_setopt($ch, CURLOPT_HEADER, 0);
	  curl_setopt($ch, CURLOPT_URL, $url);
	  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	  curl_exec($ch);
	  curl_close($ch);
  }

  public function error()
  {
    $this->view->assign("error", isset($_REQUEST["msg"]) ? $_REQUEST["msg"] : "");
    $this->display();
  }
  public function guide()
  {
    $this->display();
  }

  public function guide_add_family()
  {
    $this->display();    
  }
  public function guide_add_member()
  {
    $this->display();    
  }

  public function guide_add_photo()
  {
    $this->display();    
  }
  public function register()
  {
    /* not found user information from the table while user has a openid. */
    /* this is the first time the user visit the site */
    /* redirect to register page */


  }

  /* description: subscribe with email 
   * 
   **/
  public function subscribes()
  {
    if (!isset($_POST['email']))
      die('请返回填写email。');
    $to = $_POST['email'];

    if (!preg_match('/^[a-zA-Z0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9-_]+(\.[a-zA-Z0-9_-]+)*\.[a-zA-Z]{2,}$/', $to))
      die("您的email有误，请返回重新填写。");

    /* insert into db */
    include_once WEB_ROOT."/Public/Set/Email.php";
    $db = new M_qin_subscribes();
    $subscribe = $db->getWithEmail($to);
    if (!$subscribe || !$subscribe['id'])
      {
	$subscribe = $db->add($to);

	/* send email */
	$msg = str_replace('#email#', $to, WELCOME_CONTENT);
	$msg = str_replace('#pass#', $subscribe['pass'], $msg);
	M_Email::send($to, WELCOME_SUBJECT, $msg); 
	$this->view->assign('message', "激活邮件发送成功。验证信息已经发送到你的邮箱".$to."，请在24小时内点击邮件里的确认连接，激活您的帐号。");
      }
    else if ($subscribe['validate'] == SUBSCRIBE_STATE_VALIDATE)
      $this->view->assign('message', "非常感谢您的订阅，这个邮件地址已经订阅过了。");
    /* for expired email */
    else if ((time() - strtotime($subscribe['date'])) >= SUBSCRIBE_VALIDATE_EXPIRED)
      {
	/* send mail */
	$msg = str_replace('#email#', $to, WELCOME_CONTENT);
	$msg = str_replace('#pass#', $subscribe['pass'], $msg);
	M_Email::send($to, WELCOME_SUBJECT, $msg); 

	/* resubscribe */
	$db->resubscribe($to);
	$this->view->assign('message', "激活邮件发送成功。验证信息已经发送到你的邮箱".$to."，请在24小时内点击邮件里的确认连接，激活您的帐号。");
      }
    else if ((time() - strtotime($subscribe['date'])) < SUBSCRIBE_VALIDATE_EXPIRED)
      $this->view->assign('message', "非常感谢您的订阅，这个邮件地址还没有激活，请点击邮箱中的连接激活。");

    $this->display();
  }

  public function subscribes_validate()
  {
    if (!isset($_GET["email"]) || !isset($_GET['pass']))
      die("参数和校验码不正确，请直接点击邮箱中的连接来激活！");

    $db = new M_qin_subscribes();
    $res = $db->validate($_GET['email'], $_GET['pass']);

    $this->view->assign("validate", $res);
    $this->display();
  }
  public function links()
  {
    $links = array();
    $fp = fopen(WEB_ROOT."/Data/surnames-link.txt","r");
    while ($line = fgets($fp))
      {
	$array = explode(',', $line);
	$links[] = $array;
      }
    $this->view->assign("links", $links);
    $this->display();
  }
  public function logout()
  {
    session_destroy();
    session_unset();

    $this->redirect('users/login');
    die();
  }
  public function test()
  {
    echo 'test';
  }
  public function copyright()
  {
	  $this->display();
  }

}
//utf8编码
?>  
